package com.heeexy.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.service.AdvertiseService;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("advertise")
public class AdvertismentController {

    @Autowired
    AdvertiseService advertiseService;
    @GetMapping("list")
    public JSONObject listAdvertisement(HttpServletRequest request){
        return advertiseService.listAdvertise(CommonUtil.request2Json(request));
    }


    @PostMapping("changestatus")
    public JSONObject changeAdvertise(@RequestBody JSONObject jsonObject){
        return advertiseService.changeAdvertise(jsonObject);
    }

    /**
     * 图片上传
     */
    @CrossOrigin(origins = "http://localhost:9520/")
    @RequestMapping(value = "/uploadfile")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 在file文件夹中创建名为fileName的文件
        assert fileName != null;
        int split = fileName.lastIndexOf(".");
        // 文件后缀，用于判断上传的文件是否是合法的
        String suffix = fileName.substring(split+1,fileName.length());
        //判断文件类型，因为我这边是图片，所以只设置三种合法格式
        String url = "";
        if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)) {
            // 正确的类型，保存文件
            try {
                File path = new File(ResourceUtils.getURL("classpath:").getPath());
                File upload = new File(path.getAbsolutePath(), "static/src/img");
                if(!upload.exists()) {
                    upload.mkdirs();
                }
                String newName = System.currentTimeMillis() + "."+suffix;
                String homepath = "/home/upload/images";
                File savedFile = new File(upload + "/" + newName);
                file.transferTo(savedFile);
                url = savedFile.getAbsolutePath();
                System.out.println("图片上传完毕，存储地址为："+ url);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name",newName);
                jsonObject.put("path","src/img/"+newName);
                return  jsonObject;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else {
            //错误的类型，返回错误提示
        }

        return  CommonUtil.errorJson(ErrorEnum.E_400);
    }

}
